<!DOCTYPE html>
<head>
    <meta charset="UTF-8">
    <title>应急信息发布项目维护添加</title>
    
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link href="../../layui/css/iconfont/iconfont.css" rel="stylesheet" type="text/css">
    <link href="../../layui/css/layui.css" rel="stylesheet" type="text/css">
    <link href="../../css/style.css" rel="stylesheet" type="text/css">
    <link href="../../css/jquery-ui-1.10.4.custom.min.css" rel="stylesheet" type="text/css">
    <script src="../../layui/layui.js"></script>
    <script src="../../js/jquery-1.8.3.js"></script>
    <script src="../../js/util.js"></script>
    <script src="../../js/jquery-ui-1.10.4.custom.min.js"></script>
    <link href="../../layui/formSelects-v4.css" rel="stylesheet" />
	<script src="../../layui/formSelects-v4.js"></script>
    
    <script>
        layui.use(['table', 'form', 'jquery', 'element','layer','laydate','upload'], function () {
            var table = layui.table;
            var form = layui.form;
            var $ = layui.$;
            var upload = layui.upload;
            var layer=layui.layer;
            var user;
            var flagMgr;
            var laydate = layui.laydate;
            
            var pointName ;
            var pointId ;
            var isRepeat;
            var mapManage = "/mapManage.html";
	        laydate.render({
	             elem: '#startTime'
	             , type: 'datetime'
	             ,min:minDate()
	        });
	        laydate.render({
	             elem: '#endTime'
	             , type: 'datetime'
	             ,min:minDate()
	        });
	        
	        function minDate(){
			    var now = new Date();
			    return now.getFullYear()+"-" + (now.getMonth()+1) + "-" + now.getDate()+" "+now.getHours()+":"+now.getMinutes()+":"+now.getSeconds();
			}
			
			
            //根据城市ID查询扩展码
            function selectExtInfo(cityId) {
                var data;
                var url = '/util/findExdId?cityId=' + cityId;
                $.ajax({
                        type: 'post',
                        async: false,
                        url: url,
                        success: function (json) {
                            console.log(json.data);
                            data = json.data;
                        }, error: function () {
                            layer.msg('系统异常，请联系管理员处理!');
                        }
                    }
                );
                return data;
            }
            //动态拼接扩展码
            function appendExtId(data) {
                if (data.length != null) {
                    var options = '<option value="">请选择</option>';
                    for (var i = 0; i < data.length; i++) {
                        options += '<option value="' + data[i] + '">' + data[i] + '</option>';
                    }
                    $('#extId').html(options);
                } else {
                    $('#extId').html('<option value="">该地市下没有扩展码</option>');
                }
                form.render();
            }
            //监听区县
            form.on('select(cityId)', function (data) {
                var data2 = selectCountyId(data.value);
                appendCounty(data2);
                //appendCountyCheckBox(data2);
                var data3 = selectExtInfo(data.value);
                appendExtId(data3);
            });
            //根据城市ID查询区县
            function selectCountyId(cityId) {
                var data;
                var url = '/util/findCountyByCityId?cityId=' + cityId;
                $.ajax({
                        type: 'post',
                        async: false,
                        url: url,
                        success: function (json) {
                            data = json.data;
                        }, error: function () {
                            layer.msg('系统异常，请联系管理员处理!');
                        }
                    }
                );
                return data;
            }
            //动态拼接区县
            function appendCounty(data){
                if (data.length != null) {
                    var options = '<option value="">请选择</option>';
                    for (var i = 0; i < data.length; i++) {
                        options += '<option value="' + data[i].countyId + '">' + data[i].countyName + '</option>';
                    }
                    $('#countyId').html(options);
                } else {
                    $('#countyId').html('该地市下没有区县');
                }
                form.render();
            }
            
            //
            function qryPathName() {
                var data;
                var url = '/smsArea/findPathName';
                $.ajax({
                        type: 'post',
                        async: false,
                        url: url,
                        success: function (json) {
                            data = json.data;
                            if (data.length != null) {
                    		var options = '<option value="all">全部</option>';
                    			for (var i = 0; i < data.length; i++) {
                    				//console.info(data[i]);
                        			options += '<option value="' + data[i] + '">' + data[i] + '</option>';
                    			}
                    			$('#pathName').html(options);
                			} else {
                    			$('#pathName').html('暂无路线信息');
                			}
                form.render();
                            
                        }, error: function () {
                            layer.msg('系统异常，请联系管理员处理!');
                        }
                    }
                );
                return data;
            }
            
            form.on('select(pathName)', function (data) {
                var subStationList=selectRegionName(data.value);
                appendSubStationNames(subStationList);
            });
            
            function selectRegionName(pathName) {
                var data;
                var url = '/smsArea/findRegionName?pathName=' + pathName;
                $.ajax({
                        type: 'post',
                        async: false,
                        url: url,
                        success: function (json) {
                            data = json.data;
                        }, error: function () {
                            layer.msg('系统异常，请联系管理员处理!');
                        }
                    }
                );
                return data;
            }
            
             function appendSubStationNames(data){
                if (data.length != null) {
                    var options = '<option value="all">全部</option>';
                    for (var i = 0; i < data.length; i++) {
                        options += '<option value="' + data[i]+ '">' + data[i] + '</option>';
                    }
                    $('#subStationName').html(options);
                } else {
                    $('#subStationName').html('该路线下暂无点位');
                }
                form.render();
    		}
    
    
    		//监听项目
    		form.on('select(countyId)', function (data) {
                //var data1 = selectMgrInfo(data.value);
                //appendMgr(data1);
            });
            //根据城市ID和区县查询项目
            function selectMgrInfo(countyId) {
                var data;
                var url = '/util/findByMgrId?countyId=' + countyId;
                $.ajax({
                        type: 'post',
                        async: false,
                        url: url,
                        success: function (json) {
                            data = json.data;
                        }, error: function () {
                            layer.msg('系统异常，请联系管理员处理!');
                        }
                    }
                );
                return data;
            }
            //动态拼接项目
            function appendMgr(data) {
                if (data.length != null) {
                    var options = '<option value="">请选择</option>';
                    for (var i = 0; i < data.length; i++) {
                        options += '<option value="' + data[i].id + '">' + data[i].name + '</option>';
                    }
                    $('#mgrId').html(options);
                } else {
                    $('#mgrId').html('<option value="">该区县下没有项目</option>');
                }
                form.render();
            }
            
            
            
            $('#query').on('click', function () {
  	       		var pathName=$("#pathName").val();
  	       		console.info(pathName);
  	       		
  	       		var subStationName=$("#subStationName").val();
  	       		var subStationNameText = $("#regionName").val();
  	       		if(isNull(subStationNameText)){
  	       			console.info("xuanze");
  	       		}else{
  	       			console.info("tainxie");
  	       			subStationName = subStationNameText;
  	       		}
  	       		var mgrId=xiangmuId;
	            var startTime=$("#startTime").val();
                var endTime=$("#endTime").val();
                var countyId = $("#countyId").val();
                var regionName = $("#countyId option:selected").text();
	            var isChooseMap = $("input[name='isChooseMap']:checked").val();
	            var cityId=$("#cityId").val();
	            if(isNull(cityId)){
                    cityId="25";
                }
                if(isNull(mgrId)){
                    layer.msg("未获取到项目编号，请重新加载");
                    return false;
                }
                
                if (subStationName == null || subStationName== "") {
                            layer.msg("点位信息不能为空");
                            return false;
                        }
  	       		//console.info("----"+pathName+"---"+subStationName);
  	       		var url="../areaManage"+mapManage+"?cityId="+cityId+"&mgrId="+mgrId+"&sendStart="+startTime+"&sendEnd="+endTime
		            		+"&scopeType="+isChooseMap+"&mgrState="+"2"+"&checkState="+"2"+"&flag="+"insert";
		          	
	                
	                if(null!=countyId&&''!=countyId){
		          		url = url +"&countyId="+countyId;
	                }
	                if(null!=regionName&&''!=regionName){
	                	url = url +"&regionName="+encodeURI(regionName);
	                }
	                
	                if(null!=subStationName&&''!=subStationName){
		          		url = url +"&subStationName="+encodeURI(subStationName);
	                }
	                if(null!=pathName&&''!=pathName){
	                	url = url +"&pathName="+encodeURIComponent(pathName);
	                }
	                url=encodeURI(url); 
		            $('iframe').attr('src', url);
            });
  
            //获取mgr序列
            var xiangmuId;
			function getMgrId() {
			    var url = '/util/getMgrId';
			    $.ajax({
			            url: url,
			            type: 'post',
			            success: function (json) {
			                xiangmuId = json.data;
			            }, error: function () {
			                layer.msg('系统异常，请联系管理员处理!');
			            }
			        }
			    );
			}
			
			//判断项目名称是否重复
			function judgeMgrName(mgrName){
				var url = '/util/getMgrName';
			    $.ajax({
			            url: url,
			            type: 'post',
			            async: false,
			            data: "mgrName="+mgrName,
			            success: function (json) {
			                flagMgr = json.data;
			            }, error: function () {
			                layer.msg('系统异常，请联系管理员处理!');
			            }
			        }
			    );
			}
            //跳转地图
            $('#ditubtn').on('click', function () {
	            var mgrId=xiangmuId;
	            var startTime=$("#startTime").val();
                var endTime=$("#endTime").val();
                var countyId = $("#countyId").val();
                var regionName = $("#countyId option:selected").text();
	            var isChooseMap = $("input[name='isChooseMap']:checked").val();
	            var cityId=$("#cityId").val();
	            if(isNull(cityId)){
                    cityId="25";
                }
                if(isNull(mgrId)){
                    layer.msg("未获取到项目编号，请重新加载");
                    return false;
                }
		        if(isChooseMap==1){
		        	$("#regionChoose").show();
		            var url=mapManage+"?cityId="+cityId+"&mgrId="+mgrId+"&sendStart="+startTime+"&sendEnd="+endTime
		            		+"&scopeType="+isChooseMap+"&countyId="+countyId+"&mgrState="+"2"+"&checkState="+"2"
		            		+"&regionName="+encodeURI(regionName);
	                url=encodeURI(url); 
		            layer.open({
	                    title: '选取发送区域',
	                    type: 2,
	                    content: [url,'no'],
	                    area: ['1000px', '450px'],
	                    scrollbar: false
	                });
		        }else if(isChooseMap==2){
		            var url="/countyManage.html?cityId="+cityId+"&mgrId="+mgrId+"&sendStart="+startTime+"&sendEnd="+endTime
		            		+"&scopeType="+"0"+"&countyId="+countyId+"&mgrState="+"2"+"&checkState="+"2";
		            layer.open({
	                    title: '选取发送区域',
	                    type: 2,
	                    content: url,
	                    area: ['1000px', '550px'],
	                    scrollbar: true
	                });
		        }
            });
            //插入提交
            $('#submit').on('click', function () {
                var pointNameNow = $("#regionName").val();
                var gpsLnglats = $("#lnglatList").val();
                var remark = $("#remark").val();
                
                var param = {
                    pointId : pointId ,
                    pointName : pointNameNow ,
                    remark : remark,
                    gpsLngLats : gpsLnglats
                };
                //var index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
                var url='/xuYiPoint/pointInfoModify';
                var index ;
                $.ajax({
                    type: 'post',
                    data: param,
                    url: url,
                    async: false,
                    beforeSend: function () {
                        if (isNull(pointNameNow)) {
                            layer.msg("点位名称不能为空");
                            return false;
                        }
                        if(pointName.length>20){
			              layer.msg("点位名过长，请修改");
			              return false;
			            }
                        //判断点位经纬度信息是否符合规范
                        if(gpsLnglats.indexOf(",")==-1||gpsLnglats.indexOf("|")==-1){
                            layer.msg("请输入正确的经纬度集合！");
                            return false;
                        }else{
                            var lnglatArr1 = gpsLnglats.split("|");

                            var lnglatArr2 = gpsLnglats.split(",");
                            if(lnglatArr1.length<3){
                                layer.msg("闭合区域至少需要三个点！");
                                return false;
                            }else{
                                for(var i=0;i<lnglatArr1.length;i++){
                                    if(lnglatArr1[i].split(",").length%2!=0){
                                        layer.msg("请输入正确的经纬度集合！");
                                        return false;
                                    }else{
                                        var lnglat = lnglatArr1[i].split(",");
                                        if(isNull(lnglat[0])||isNull(lnglat[1])){
                                            layer.msg("请输入正确的经纬度集合！");
                                            return false;
                                        }
                                        if(!checkLng(lnglat[0])){
                                            layer.msg("点位经度数据格式有误！");
                                            return false;
                                        }
                                        if(!checkLat(lnglat[1])){
                                            layer.msg("点位纬度数据格式有误！");
                                            return false;
                                        }

                                    }
                                }
                            }
                        }


                        if(pointNameNow==pointName){
                            console.info("name no change");
                        }else{

                            judgePointName(pointNameNow);

                            if(isRepeat){
                                console.info("test");
                                layer.msg("该点位名称已存在！");
                                return false;
                            }
                        }


			            index = layer.load(1, {shade: [0.1,'#fff'] });//0.1透明度的白色背景
                    },
                    success: function (json) {
                        if (json.code == 0) {
                            layui.use('layer', function () {
                                layer.msg('操作成功,待审核！点击确认返回点位管理界面', {
                                    time: 0 //不自动关闭
                                    , btn: ['确定']
                                    , yes: function (index2) {
                                    	layer.close(index);
                                        layer.close(index2);
                                        location.href = "xuYiSubStationManage.html";
                                    }
                                });
                            }); 
                        }else {
                        	layer.close(index);
                            layer.msg(json.msg);
                        }
                    },
                    complete: function () {

                    },
                    error: function (data) {
                    	layer.close(index);
                        layer.msg('系统异常，请联系管理员处理!');
                    }
                });
            });
            $('#nextStep').on('click', function () {
				var cityId=$("#cityId").val();
				if (isNull(cityId)) {
					cityId="25";
                }
                var countyId = $("#countyId").val();
                var name = $("#name").val();
                judgeMgrName(name);
                var extId=$("#extId").val();
                var startTime=$("#startTime").val();
                var endTime=$("#endTime").val();
                var content=$("#content").val();
                var localDate=$("input[name='localDate']:checked").val();
                var isThreshold = 0;
                $("input:checkbox[name='isThreshold']:checked").each(function () {
                    isThreshold += parseInt($(this).val());
                });
                var cycleThreshold=0;
                var cycle;
                if(isThreshold==2||isThreshold==3){
                	//var cycle = $("input[name='cycle']:checked").val();     //发送周期
                	cycle=$("#cycle").val();
                	cycleThreshold=$("#cycleThreshold").val();
                }
                var isChooseMap = $("input[name='isChooseMap']:checked").val();
		        //var xiangmuid=$("#xiangmuid").val();
		        var xiangmuid=xiangmuId;
                var quyuid=$("#quyuid").val();
                var quyutype=$("#quyutype").val();
                var quyudetail=$("#quyudetail").val();
                var scopeType = $("input[name='isChooseMap']:checked").val();
                var param = {
                    cityId: cityId,
                    countyId: countyId,
                    name: name,
                    extId: extId,
                    startTime: startTime,   //项目开始时间
                    endTime: endTime,//结束时间
                    isLocal: $("input[name='isLocal']:checked").val(),//是否本地发送
                    threshold: $("#threshold").val(),  //全部阀值
                    isThreshold: isThreshold,
                    content:content,
                    mgrId:xiangmuid,
                    regionId:quyuid,
                    regionType:quyutype,
                    regionTypeValue:quyudetail,
                    cycle:cycle,
                    cycleThreshold: cycleThreshold,//周期阀值
                    localDate:localDate,
                    flag: "insert"
                };
                var index = layer.load(1, {shade: [0.1,'#fff'] });
                var url='/mgrTemplate/configureMgrTemplate';
                $.ajax({
                    type: 'post',
                    data: param,
                    url: url,
                    async: false,
                    beforeSend: function () {
                        if (isNull(name)) {
                            layer.msg("项目名称不能为空");
                            layer.close(index);
                            return false;
                        }
                        if (startTime == null || startTime== "") {
                            layer.msg("发送开始时间不能为空");
                            layer.close(index);
                            return false;
                        }
                        if (endTime == null || endTime == "") {
                            layer.msg("发送结束时间不能为空");
                            layer.close(index);
                            return false;
                        }
                        if (!checkRate($("#threshold").val())) {
                            layer.msg("阀值必须为数字");
                            layer.close(index);
                            return false;
                        }
                        if (isNull(content)) {
                            layer.msg("短信内容不能为空");
                            layer.close(index);
                            return false;
                        }
                        if (startTime>=endTime) {
                            layer.msg("发送结束时间不能小于等于开始时间");
                            layer.close(index);
                            return false;
                        }
                        if(flagMgr!=0){
                    		layer.msg("项目名重复，请修改");
                    		layer.close(index);
                            return false;
                    	}
                    	if(name.length>20){
			              layer.msg("项目名过长，请修改");
			              layer.close(index);
			              return false;
			            }
                    },
                    success: function (json) {
                        if (json.code == 0) {
                            layui.use('layer', function () {
                                layer.msg('项目添加成功,点击确认配置短信项目发送范围', {
                                    time: 0 //不自动关闭
                                    , btn: ['确定']
                                    , yes: function (index2) {
                                    	layer.close(index);
                                    	layer.close(index2);
                                        $(".layui-form-item").css("display","none");
									   	$("#sendLimit").css("display","inline");
									   	$("#chooseSendLimit").css("display","inline");
									   	$("#ditu").css("display","inline");
									   	chooseSendLimitType();
                                    }
                                });
                            }); 
                        }else {
                        	layer.close(index);
                            layer.msg(json.msg);
                        }
                       
                       
                    },
                    complete: function () {

                    },
                    error: function (data) {
                    	layer.close(index);
                        layer.msg('系统异常，请联系管理员处理!');
                    }
                }); 
            });


            //判断点位名称是否重复
            function judgePointName(pointName){
                var pointName = $("#regionName").val();
                var url = '/xuYiPoint/findPointInfoByName';
                var param = {
                    pointName : pointName
                };

                $.ajax({
                        url: url,
                        type: 'post',
                        async: false,
                        data: param,
                        success: function (json) {
                            console.info(json.data);
                            var id = json.data.id ;
                            if(id == null || id == undefined || id == '' ){
                                isRepeat = false;
                            }else{
                                isRepeat = true;

                            };

                            console.info(isRepeat);
                        }, error: function () {
                            layer.msg('系统异常，请联系管理员处理!');
                        }
                    }
                );
            }


            //身份识别
            $(document).ready(function () {
                pointName = decodeURI(decodeURIComponent(getUrlParam("pointName")));
                console.info("pointName = "+pointName);
            	var url = '/xuYiPoint/findPointInfoByName';
                var param = {
                    pointName: pointName
                };
                $.ajax({
                    type: 'post',
                    async: false,
                    url: url,
                    data: param,
                    beforeSend: function () {
                        loading = layer.load(0, {shade: false});
                    },
                    success: function (json) {
                        layer.close(loading);
                        var data = json.data;
                        console.info("---"+data);
                        pointId = data.id;
                        $("#regionName").val(pointName);
                        $("#lnglatList").val(data.gpsLngLats);
                        $("#remark").val(data.remark);
                        form.render();                     
                    },
                    error: function (data) {
                        layer.msg('系统异常，请联系管理员处理!');
                    }
                });
            });
            //校验字符串
			function checkStr(str,defaultVal){
				if (typeof(str) == "undefined" || str == null || str == "null") {
					if (defaultVal == undefined) {
						str = "";
					} else {
						str = defaultVal;
					}
				}
				return str;
		    }
		    
		    //上传变电站文件
		    upload.render({
					elem : '#import2',
					url : '/xuYi/importSubStation',
					auto : false, //关闭自动上传
					accept : 'file', //普通文件
					exts : 'csv', //只允许上传csv文件 //,multiple: true
					bindAction : '#uploadFile2',
					before : function() {
						layer.load(); //上传loading
					},done : function(obj) {
						console.info(obj);
						layer.closeAll('loading'); //关闭loading
						if (obj.code == 0 && obj.data!=null) {
							var data = obj.data;
							layer.confirm('成功导入' +data + '个变电站', {
								btn: ['确定'] //按钮
							}, function () {
								location.href="xuYiSubStationManage.html";
							});
    					}
						else{
			               l
			            }
						/* if (obj.code > 0) {
							layer.msg(obj.msg);
						} */
		
					},
					error : function(index, upload) {
						layer.closeAll('loading'); //关闭loading
						layer.msg("上传过程中出现异常，请重试");
					}
				});
		    
		    
		    form.on("radio(insertType)", function (data) {
		    	var insertType = $("input[name='insertType']:checked").val();
		    		//选择单个点位录入
				if(insertType==="single"){
		        	$("#singleInsert").show();
		        	$("#totalInsert").hide();
		        }else if(insertType==="total"){
		        	//选择批量点位录入
		        	$("#singleInsert").hide();
		        	$("#totalInsert").show();
		        }
		    });

            $('#back').on('click', function (){
                window.location.href="xuYiSubStationManage.html";
            });

            $('#back').on('click', function (){
                window.location.href="xuYiStationManage.html";
            });
        });
    </script>
</head>
<body>
<div class="layui-html-limit">
    <!--container-->
    <div class="layui-content-body">
        <div class="scroll-box">
            <div class="breadcrumb-box">
              <span class="layui-breadcrumb" lay-separator="|">
                  <a href="javascript:returnIndex2()">首页&nbsp;</a>
                  <a href="#"> &nbsp;点位信息变更&nbsp; </a>
              </span>
            </div>
            <div class="content-box" style="height:100%;width:100%;">
                <div class="layui-form layui-form-pane" style="height:100%;width:110%;" >
                	<div id = "singleInsert">
                    <div class="layui-form-item" >
                        <div class="layui-block" pane="">
                            <label class="layui-form-label" style="width:120px">点位名称</label>
                            <div class="layui-input-block" style="width:180px;margin-left:120px;">
			                    <input type="text" name="regionName" id="regionName" required lay-verify="required" 
			                           placeholder="请输入点位名称"
			                           autocomplete="off" class="layui-input">
			                </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-block">
                            <label class="layui-form-label" style="width: auto">&nbsp;点位经纬集合</label>
                            <div class="layui-input-block">
                            	<textarea placeholder="经度纬度之间以英文逗号隔开，多个经纬度以  ‘ | ’ 分隔 ，如 118.8888,31.8888|118.6666,31.6666|118.9999,31.9999" class="layui-textarea" style="width: 35%"
                                      id="lnglatList"></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-block">
                            <label class="layui-form-label" style="width: auto">&nbsp;点位信息备注</label>
                            <div class="layui-input-block">
                            	<textarea placeholder="请输入内容" class="layui-textarea" style="width: 50%"
                                      id="remark"></textarea>
                            </div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <!-- <button class="layui-btn" id="submit">立即提交</button> -->
                        <button class="layui-btn" id="submit">确认修改</button>
                        <button class="layui-btn" id="back">返回</button>
                    </div>
                  </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>